package com.dib.neo.bkfs.fs;


import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Set;

class BKFileModeAttribute {

  static final int ALL_PERMISSIONS =
      BKConstants.S_IRUSR | BKConstants.S_IWUSR | BKConstants.S_IXUSR |
          BKConstants.S_IRGRP | BKConstants.S_IWGRP | BKConstants.S_IXGRP |
          BKConstants.S_IROTH | BKConstants.S_IWOTH | BKConstants.S_IXOTH;

  static final int ALL_READWRITE =
      BKConstants.S_IRUSR | BKConstants.S_IWUSR |
          BKConstants.S_IRGRP | BKConstants.S_IWGRP |
          BKConstants.S_IROTH | BKConstants.S_IWOTH;

  static final int TEMPFILE_PERMISSIONS =
      BKConstants.S_IRUSR | BKConstants.S_IWUSR | BKConstants.S_IXUSR;

  private BKFileModeAttribute() {
  }

  static int toUnixMode(Set<PosixFilePermission> perms) {
    int mode = 0;
    for (PosixFilePermission perm : perms) {
        if (perm == null) {
            throw new NullPointerException();
        }
      switch (perm) {
        case OWNER_READ:
          mode |= BKConstants.S_IRUSR;
          break;
        case OWNER_WRITE:
          mode |= BKConstants.S_IWUSR;
          break;
        case OWNER_EXECUTE:
          mode |= BKConstants.S_IXUSR;
          break;
        case GROUP_READ:
          mode |= BKConstants.S_IRGRP;
          break;
        case GROUP_WRITE:
          mode |= BKConstants.S_IWGRP;
          break;
        case GROUP_EXECUTE:
          mode |= BKConstants.S_IXGRP;
          break;
        case OTHERS_READ:
          mode |= BKConstants.S_IROTH;
          break;
        case OTHERS_WRITE:
          mode |= BKConstants.S_IWOTH;
          break;
        case OTHERS_EXECUTE:
          mode |= BKConstants.S_IXOTH;
          break;
      }
    }
    return mode;
  }

  @SuppressWarnings("unchecked")
  static int toUnixMode(int defaultMode, FileAttribute<?>... attrs) {
    int mode = defaultMode;
    for (FileAttribute<?> attr : attrs) {
      String name = attr.name();
      if (!name.equals("posix:permissions") && !name.equals("unix:permissions")) {
        throw new UnsupportedOperationException("'" + attr.name() +
            "' not supported as initial attribute");
      }
      mode = toUnixMode((Set<PosixFilePermission>) attr.value());
    }
    return mode;
  }
}
